<template>
  <div>
    <!-- 搜索栏 -->
    <Row style="margin:20px 0;">
      <Card>
        <div style="margin-top: 6px">
          <Form ref="searchData" :model="searchData" :label-width="80">
            <Row>
                    <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="加分类别" prop="typeClass">
                  <Input
                    search
                    placeholder="请输入加分类别"
                    v-model="searchData.typeClass"
                    style="width: auto"
                  >
                    <Icon type="ios-search" slot="suffix" />
                  </Input>
                </FormItem>
              </i-col>
              <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="类别名称" prop="typeName">
                  <Input
                    search
                    placeholder="请输入类别名称"
                    v-model="searchData.typeName"
                    style="width: auto"
                  >
                    <Icon type="ios-search" slot="suffix" />
                  </Input>
                </FormItem>
              </i-col>
              <i-col :xs="24" :md="12" :lg="6">
                <FormItem label="年份" prop="datetime">
                  <DatePicker
                    type="year"
                    format="yyyy"
                    :value="searchData.datetime"
                    @on-change="handleFormat2"
                    placeholder="请选择年份"
                    style="width:185px"
                  ></DatePicker>
                </FormItem>
              </i-col>
            </Row>
            <FormItem>
              <Button type="primary"  @click="searchSubmit()">提交搜索</Button>
              <Button@click="seachReset('searchData')" style="margin-left: 8px">重置搜索</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </Row>

    <!-- 上传 -->
    <Card style="margin-bottom:10px;" title="导入EXCEL">
      <Alert show-icon style="width:600px;">当导入文件中年份和加分类别与系统中存在信息一致的时候，该条数据不会被替换</Alert>
      <Upload
        ref="upload"
        :before-upload="handleUpload"
        :on-success="handleSuccess"
        :format="['xls','xlsx']"
        :on-format-error="handleFormatError"
        :action="importUrl"
      >
        <Button type="success" @click="downLoad" style="margin-right:20px;">下载事项类别定制模板</Button>
        <Tooltip content="温馨提示：导入文件请先下载模板，依照模板格式上传" placement="top-start" max-width="220">
          <Button type="primary" icon="ios-cloud-upload-outline">导入事项类别定制</Button>
        </Tooltip>
      </Upload>
      <div v-if="file !== null">
        文件名: {{ file.name }}
        <Button type="primary" @click="upload">确认导入</Button>
      </div>
    </Card>

    <!-- 添加 -->
    <Card>
      <div class="btn-arrs">
         <Button type="info" @click="openAddpointModal">添加加分类别</Button>
      </div>
      <Table
        border
        :loading="tabelLoading"
        :columns="categoryHead"
        :data="categoryData"
      ></Table>
    </Card>

    <!-- 加分类别弹窗  -->
    <Modal v-model="categoryModal" :title="categoryTitle" @on-cancel="cancelCategoryModal">
      <Form ref="categoryForm" :model="categoryForm" :rules="categoryReg" :label-width="80">
        <FormItem label="类别名称" prop="typeName">
          <Input v-model="categoryForm.typeName" placeholder="请输入类别名称"></Input>
        </FormItem>
        <FormItem label="年份" prop="datetime">
          <DatePicker
            type="year"
            format="yyyy"
            :value="categoryForm.datetime"
            @on-change="handleFormat"
            placeholder="请选择年份"
            style="width:185px"
          ></DatePicker>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" size="large" @click="submitCategory('categoryForm')">提交</Button>
        <Button size="large" @click="cancelCategoryModal">取消</Button>
      </div>
    </Modal>

    <!-- 增加/编辑类别选项 -->
    <Modal v-model="optionsModal" title="编辑类别选项" width="800" @on-cancel="cancelOptions">
      <Form id="categoryOptions" ref="categoryOptionsForm" v-model="categoryOptionsForm">
        <!-- :prop="'itemList.' + index + '.itemName'"
        :rules="{required: true, message: '类别选项不能为空', trigger: 'blur'}"-->
        <FormItem
          v-for="(item, index) in categoryOptionsForm.itemList"
          v-if="item.status"
          :key="index"
          label="类别选项"
        >
          <Row>
            <Col span="17">
              <Input type="textarea" v-model="item.itemName" placeholder="请输入类别选项"></Input>
            </Col>
            <Col span="2" offset="1">
              <Button type="error" @click="handleRemove(index)">删除</Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <Row>
            <Col span="5" offset="2">
              <Button type="success" long ghost @click="handleAdd" icon="md-add">添加选项类别</Button>
            </Col>
          </Row>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmit('categoryOptionsForm')">提交</Button>
        <Button @click="cancelOptions" size="large">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { categoryAjax } from "@/api/incentives";
import { URL } from "@/libs/util";
// 以防命名冲突
const HOST = URL;
// 查询路径
const QUERYTYPE_URL = "/incentiveType/queryType";
// 添加类别
const ADDTYPE_URL = "/incentiveType/insertType";
// 修改类别
const UPDTYPE_URL = "/incentiveType/updateType";
// 删除类别类别
const DELTYPE_URL = "/incentiveType/deleteType";
// 添加类别选项
const ADDOPTIONS_URL = "/incentiveType/insertItems";
// 修改类别选项
const UPDOPTION_URL = "/incentiveType/updateItems";
// 删除类别选项
const DELOPTION_URL = "/incentiveType/deleteItems";
export default {
  data() {
    return {
      tabelLoading: false,
      // 类别表格
      categoryHead: [
        {
          title: "年份",
          key: "datetime",
          width: 100
        },
        {
          title: "类别名称",
          key: "typeName"
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 500,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.categoryForm = JSON.parse(
                        JSON.stringify(params.row)
                      );
                      console.log(params.row);
                      this.categoryTitle = "编辑加分类别";
                      this.categoryModal = true;
                    }
                  }
                },
                "编辑加分类别"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.categoryForm = JSON.parse(
                        JSON.stringify(params.row)
                      );
                      this.delCategory(params.row);
                    }
                  }
                },
                "删除加分类别"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.optionsModal = true;
                      this.categoryOptionsForm = JSON.parse(
                        JSON.stringify(params.row)
                      );
                      let parent = params.row.itemList; // 选项数据
                      let newList = []; // 重新组装数据
                      parent.forEach(item => {
                        newList.push({
                          index: item.id,
                          itemId: item.id,
                          id: item.id,
                          status: 1,
                          itemName: item.itemName
                        });
                      });
                      this.categoryOptionsForm.itemList = newList; // 赋值选项值
                      this.list = parent;
                    }
                  }
                },
                "添加/编辑类别选项"
              )
            ]);
          }
        }
      ],
      categoryData: [],
      // 加分类别模态框
      categoryModal: false,
      categoryForm: {
        typeName: "", // 类别名称
        datetime: "",
        typeClass: "" // 加分类别
      },
      categoryTitle: "添加加分类别",
      // 类别选项
      optionsModal: false,
      categoryOptionsForm: {
        itemList: [
          {
            itemName: "",
            index: 1,
            status: 1
          }
        ]
      },
      index: 1,
      list: [], // 存放类别选项数组
      file: null,
      // 导入事项类别定制路径
      importUrl: URL + "/incentiveType/importIncentiveType",
      searchData: {
        typeName: "", // 类别名称
        datetime: "",
        typeClass: "" // 加分类别
      },
      categoryReg: {
        typeName: [
          {
            required: true,
            message: "请输入类别名称",
            trigger: "blur"
          }
        ],
        typeClass: [
          {
            required: true,
            message: "请输入加分类别",
            trigger: "blur"
          }
        ],
        datetime: [
          {
            required: true,
            type: "string",
            message: "请选择时间",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    // 打开加分类别弹窗
    openAddpointModal() {
      // debugger;
      this.$refs["categoryForm"].resetFields();
      this.categoryTitle = "添加加分类别";
      this.categoryModal = true;
    },
    cancelCategoryModal() {
      this.categoryModal = false;
      this.$refs['categoryForm'].resetFields();
    },
    // 提交加分类别模态框
    submitCategory(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.categoryTitle === "添加加分类别") {
            this._categoryAjax(this.categoryForm, ADDTYPE_URL).then(result => {
              this.categoryModal = false;
              if (result.code === "200") {
                this.$Message.success(result.message);
                this._getData("", QUERYTYPE_URL);
              } else {
                this.$Message.error(result.message);
              }
            });
          } else if (this.categoryTitle === "编辑加分类别") {
            this._categoryAjax(this.categoryForm, UPDTYPE_URL).then(result => {
              this.categoryModal = false;
              if (result.code === "200") {
                this.$Message.success(result.message);
                this._getData("", QUERYTYPE_URL);
              } else {
                this.$Message.error(result.message);
              }
            });
          }
          this.categoryModal = false;
        } else {
          this.$Message.error("带*为必填项");
        }
      });
    },
    // 删除加分类别
    delCategory(row) {
      this.$Modal.confirm({
        title: "删除加分类别",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          this._categoryAjax(this.categoryForm, DELTYPE_URL).then(result => {
            this.$Modal.remove();
            if (result.code === "200") {
              this.$Message.success(result.message);
              this._getData("", QUERYTYPE_URL);
            } else {
              this.$Message.error(result.message);
            }
          });
        }
      });
    },
    cancelOptions() {
      this.optionsModal = false;
    },
    // 类别选项
    openOptions() {
      this.optionsModal = true;
    },
    // 提交类别选项
    handleSubmit() {
      let arr = []; // 存放未隐藏的选项
      this.categoryOptionsForm.itemList.forEach(item => {
        if (item.status === 1) {
          arr.push(item);
        }
      });
      this.categoryOptionsForm.itemList = arr; // 重新赋值
      let formData = this.categoryOptionsForm;
      // 数组为空就添加/不为空就修改
      if (this.list.length === 0) {
        this._addOrUpdAjax(formData, ADDOPTIONS_URL).then(result => {
          this.optionsModal = false;
          if (result.code === "200") {
            this.$Message.success(result.message);
            // 重新查询
            this._getData("", QUERYTYPE_URL);
          } else {
            this.$Message.error(result.message);
          }
        });
      } else if (this.list.length !== 0) {
        this._addOrUpdAjax(formData, UPDOPTION_URL).then(result => {
          this.optionsModal = false;
          if (result.code === "200") {
            this.$Message.success(result.message);
            // 重新查询
            this._getData("", QUERYTYPE_URL);
          } else {
            this.$Message.error(result.message);
          }
        });
      }
    },
    // 添加/修改小类请求
    _addOrUpdAjax(formData, url) {
      const keyOne = "filter";
      return new Promise((resolve, reject) => {
        categoryAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 增加类别选项
    handleAdd() {
      this.index++;
      this.categoryOptionsForm.itemList.push({
        itemName: "",
        index: this.index,
        status: 1
      });
    },
    // 删除类别选项
    handleRemove(index) {
      //
      this.$Modal.confirm({
        title: "删除该类别选项",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          const keyOne = "filter";
          const url = "/incentiveType/deleteItems";
          let itemId = this.categoryOptionsForm.itemList[index].itemId;
          let formData = { itemId: itemId };
          if (itemId === undefined) {
            this.categoryOptionsForm.itemList[index].status = 0; // 删除成功改变状态隐藏
            this.$Modal.remove();
            return;
          }
          this._addOrUpdAjax(formData, DELOPTION_URL).then(result => {
            this.$Modal.remove();
            this.optionsModal = false;
            if (result.code === "200") {
              this.$Message.success(result.message);
              this.categoryOptionsForm.itemList[index].status = 0; // 删除成功改变状态隐藏
              // 重新查询
              this._getData("", QUERYTYPE_URL);
            } else {
              this.$Message.error(result.message);
            }
          });
        }
      });
    },
    // 查询类别
    _getData(formData, url) {
      this.tabelLoading = true;
      const keyOne = "typeEntity";
      categoryAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.categoryData = result.data.results.list;
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 添加/修改类别
    _categoryAjax(formData, url) {
      const keyOne = "typeEntity";
      return new Promise((resolve, reject) => {
        categoryAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 导入方法
    handleUpload(file) {
      this.file = file;
      return false;
    },
    upload() {
      this.$refs.upload.post(this.file); // 请求
      setTimeout(() => {
        this.file = null;
      }, 1500);
    },
    // 上传文件
    handleSuccess(res, file) {
      if (res.code === "200") {
        this.$Notice.success({
          title: res.message
        });
        this._getData("", QUERYTYPE_URL);
      } else if (res.code === "500") {
        this.$Notice.error({
          title: res.message
        });
      }
    },
    // 验证上传格式
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式错误",
        desc: "文件" + file.name + " 格式错误, 请选择xls或者xlsx"
      });
    },
    // FORM表单年份
    handleFormat(year) {
      this.categoryForm.datetime = year;
    },
    // 搜索年份
    handleFormat2(year) {
      this.searchData.datetime = year;
    },
    /**
     * 下载事项类别定制模板
     */
    downLoad() {
      window.open(
        HOST +
          "/townScore/downTownScoreMoudle?fileName=incentiveMould.xls&chinaName=定制类别导入模板.xls"
      );
    },
    seachReset(name) {
      this.$refs[name].resetFields();
    },
    // 搜索
    searchSubmit() {
      this._getData(this.searchData, QUERYTYPE_URL);
    }
  },
  created() {
    this._getData("", QUERYTYPE_URL);
  }
};
</script>
<style>
#categoryOptions .ivu-form-item-error-tip {
  left: 70px;
}
</style>
